package com.killer.controller;

import com.killer.pojo.Token;
import com.killer.pojo.User;
import com.killer.service.user.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author ：Killer
 * @date ：Created in 20-12-31 下午2:58
 * @description：${description}
 * @modified By：
 * @version: version
 */
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @RequestMapping("/register/{email}/{password}/{code}")
    public Boolean register(@PathVariable String email,
                            @PathVariable String password,
                            @PathVariable String code){
        try {
            userService.register(email, password, code);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    @RequestMapping("/isRegistered/{email}")
    public Boolean checkRegistered(@PathVariable String email) {
        User user = userService.getUserByEmail(email);
        return user!=null;
    }


    @RequestMapping("/login/{email}/{password}")
    public void login(@PathVariable String email, @PathVariable String password, HttpServletRequest request, HttpServletResponse response) throws IOException {
        //登录获取tonken
        String token = userService.login(email, password);
        //将token写入cookie
        // Cookie 为键值对数据格式
        Cookie cookie = new Cookie("token", token);
        // 即：过期时间，单位是：秒（s）
        cookie.setMaxAge(30 * 24 * 60 * 60);
        // 表示当前项目下都携带这个cookie
        cookie.setPath("/");
        //向客户端发送 Cookie
        response.addCookie(cookie);
        response.sendRedirect("http://8.129.231.238/welcome.html");
    }

    @RequestMapping("/info/{token}")
    public String getUserInfo(@PathVariable String token) {
        Token tokenInfo = userService.getTokenbyToken(token);
        if (tokenInfo == null) {
            throw new RuntimeException("该token不存在");
        }
        return tokenInfo.getEmail();
    }
}
